/*
 * Copyright (c) 2024. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.neusoft.tyut.myspring.mybatisdemo.mapper;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseMapper {
    public Connection getConnection() throws SQLException, ClassNotFoundException {
        //        Class.forName("org.")
        //        return DriverManager.getConnection("jdbc:mysql://localhost:3306/mybatis", "root",
        // "123456");
        return null;
    }

    // selec  from  where a = ? and b = ? and c = ?
    public List<Map<String, Object>> query(String sql, Object[] args) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        //        为占位符赋值
        for (int i = 0; i < args.length; i++) {
            preparedStatement.setObject(i + 1, args[i]);
        }
        ResultSet resultSet = preparedStatement.executeQuery();
        ResultSetMetaData metaData = resultSet.getMetaData();
        int columnCount = metaData.getColumnCount();
        List<String> cloumnNames = new ArrayList<>();

        for (int i = 0; i < columnCount; i++) {
            cloumnNames.add(metaData.getColumnName(i + 1)); // deptno, dname, loc
        }
        List<Map<String, Object>> list = new ArrayList<>();
        while (resultSet.next()) {
            Map<String, Object> map = new HashMap<>();
            for (int i = 0; i < columnCount; i++) {
                String cloumnName = cloumnNames.get(i);
                map.put(cloumnName, resultSet.getObject(cloumnName));
                list.add(map);
            }
        }
        connection.close();
        return list;
    }

    public int update(String sql, Object[] args) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < args.length; i++) {
            preparedStatement.setObject(i + 1, args[i]);
        }
        preparedStatement.executeUpdate();
        return -1;
    }
}
